package cn.hesion.dataStructures.Stack;

public class LinkedListStack {

    private LLNode head = null;
    private int size = 0; //记录栈中元素个数

    public LinkedListStack() {
        this.head = new LLNode(null);
    }

    public boolean isEmpty() {
        return head.getNext() == null;
    }

    public void push(Object data) {
        if (head.getNext() == null) {
            head.setNext(new LLNode(data));
            size++;
        } else {
            //先记录原先的栈顶元素
            LLNode oldTopNode = head.getNext();
            //创建一个新的节点，待会通过头插法插入链表
            LLNode newNode = new LLNode(data);
            //1.将head的next链接到新节点newNode上
            head.setNext(newNode);
            //新节点的next链接到原先的栈顶节点上
            newNode.setNext(oldTopNode);
            size++;
        }
    }

    public Object pop() {
        if (isEmpty()) {
            throw new RuntimeException("栈已空");
        }
        // 记录栈顶节点元素
        LLNode topNode = head.getNext();
        head.setNext(topNode.getNext());
        size--;
        return topNode.getData();

    }

    public int getNumInStack() {
        return size;
    }

    public void list() {

        if (head.getNext() == null) {
            System.out.println("栈为空");
            return;
        }
        LLNode temp = head.getNext();
        System.out.println("栈中元素有:");
        while (true) {
            if (temp.getNext() == null) {
                // 这一步的目的是找到尾节点
                System.out.println(temp.getData());
                break;
            }
            System.out.println(temp.getData());
            temp = temp.getNext();
        }
    }
}